package cn.sunxinao.pm.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * 工具类
 */
public class Common {
    private Common() {
        throw new IllegalStateException("这里面只有静态方法，所以禁止实例化");
    }

    /**
     * 获取字符串的md5散列值(十六进制)
     * 如果传入的值为空，则返回空白字符串
     *
     * @param str 加密内容
     * @return 十六进制哈希
     */
    public static String md5Hex(String str) {
        if (str == null || str.isEmpty()) return "";
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(str.getBytes());
            byte[] dist = messageDigest.digest();
            StringBuilder sb = new StringBuilder();
            for (byte b : dist) {
                sb.append(Integer.toHexString((0x000000ff & b) | 0xffffff00).substring(6));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取随机字符串(字符集:[0-9a-zA-Z])
     *
     * @param length 长度
     * @return 随机字符串
     */
    public static String randString(int length) {
        String base = "1234567890abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < length; i++)
            result.append(base.charAt(new Random().nextInt(base.length())));
        return result.toString();
    }
}
